
import 'package:flutter/cupertino.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:syn_4s/core/utils/sp_utils.dart';
import 'package:syn_4s/generated/l10n.dart';

import '../constants/sp_key.dart';

/// 位置服务
Future<Position> determinePosition(BuildContext context) async {
  bool serviceEnabled;
  LocationPermission permission;
  /// 手机GPS服务是否已启用。
  serviceEnabled = await Geolocator.isLocationServiceEnabled();
  if (!serviceEnabled) {
    //定位服务未启用，要求用户启用定位服务
    var res = await Geolocator.openLocationSettings();
    if (!res) {
      /// 被拒绝
      // HLog("已拒绝定位服务未启用", StackTrace.current);
      return Future.error(S.of(context).service_not_enabled);
    }
  }
  /// 是否允许app访问地理位置
  permission = await Geolocator.checkPermission();

  if (permission == LocationPermission.denied) {
    /// 之前访问设备位置的权限被拒绝，重新申请权限
    permission = await Geolocator.requestPermission();
    if (permission == LocationPermission.denied) {
      /// 再次被拒绝。根据Android指南，你的应用现在应该显示一个解释性UI。
      return Future.error(S.of(context).location_permission_denied);
    }
  }
  if (permission == LocationPermission.deniedForever) {
    /// 之前权限被永久拒绝，打开app权限设置页面
    await Geolocator.openAppSettings();
    return Future.error(S.of(context).permission_permanently_denied);
  }
  /// 允许访问地理位置，获取地理位置
  return await Geolocator.getCurrentPosition(locationSettings: LocationSettings(accuracy: LocationAccuracy.high));
}

Future<List<Placemark>> getLocationInfo(BuildContext context) async {
  int languageId = await SPUtils.get(keyLanguage) ?? 1;
  String localeIdentifier = languageId == 1 ? "zh-TW,zh" : "en-US,en";
  return determinePosition(context).then((location)=> placemarkFromCoordinates(location.latitude, location.longitude, localeIdentifier: localeIdentifier));
}

Future<bool> checkWritePermission() async {
  var status = await Permission.storage.status;
  if (status.isDenied || status.isRestricted) {
    // 用户拒绝或限制，请求权限
    await Permission.storage.request();
    // 再次检查权限
    status = await Permission.storage.status;
  }
  // 返回权限状态
  return status.isGranted;
}